import fs from 'fs';
import path from 'path';
import csv from 'csv-parser';

const EXPLOITDB_CSV_PATH = path.join(process.cwd(), 'data', 'exploitdb', 'files_exploits.csv');

export async function fetchExploitDB() {
  return new Promise<any[]>((resolve) => {
    const results: any[] = [];

    try {
      fs.createReadStream(EXPLOITDB_CSV_PATH)
        .pipe(csv())
        .on('data', (row) => {
          const edbId = row.id?.trim();
          const description = row.description?.trim();
          const rawDate = row.date_published?.trim();
          const codes = row.codes?.trim();

          const cveMatches = [
            ...(description?.match(/CVE-\d{4}-\d{4,}/g) || []),
            ...(codes?.match(/CVE-\d{4}-\d{4,}/g) || [])
          ];

          const parsedDate = rawDate && !isNaN(Date.parse(rawDate))
            ? new Date(rawDate).toISOString()
            : new Date().toISOString();

          for (const cveId of cveMatches) {
            const cvss = /critical|remote code execution|rce|privilege escalation|buffer overflow/i.test(description)
              ? 9.0
              : /denial of service|dos|xss|csrf|bypass/i.test(description)
              ? 6.0
              : /info|disclosure|leak|minor/i.test(description)
              ? 3.0
              : 0;

            results.push({
              id: cveId,
              description: description || 'No description',
              published: parsedDate,
              source: 'ExploitDB',
              link: `https://www.exploit-db.com/exploits/${edbId}`,
              cvss,
            });
          }
        })
        .on('end', () => {
          console.log(`💣 Loaded ${results.length} ExploitDB entries`);
          resolve(results);
        })
        .on('error', (err) => {
          console.error('❌ ExploitDB CSV parse error:', err);
          resolve([]); // fallback instead of reject
        });
    } catch (err) {
      const error = err as Error;
      console.log('⚠️ ExploitDB file missing:', error.message);
      resolve([]);
    }
  });
}
